#include "../../h/apue.h"
#include <fcntl.h>

#define READ_PER 1

int main(int argc, char ** argv)
{
    int fd1, fd2;
    char buf[READ_PER];
    int n;

    struct stat stbuf;
    mode_t fmode = FILE_MODE;

    if (argc != 3)
        err_quit("Usage %s <srcname> <newname>.", argv[0]);

    if ((fd1 = open(argv[1], O_RDONLY, FILE_MODE)) < 0)
        err_sys("open file %s failed", argv[1]);

    if (stat(argv[2], &stbuf) == 0)
        fmode = stbuf.st_mode;

    if ((fd2 = creat(argv[2], fmode)) < 0)
        err_sys("creat file %s failed", argv[2]);

    while (( n = read(fd1, buf, READ_PER) ) > 0)
        if (buf[0] != 0)
            if (write(fd2, buf, n) != n)
                err_sys("write error");

    puts("Done.");
}
